package com.crm.system.service.impl.systemManager;

import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.systemManager.CallManager;
import com.crm.model.qo.systemManager.CallManagerQO;
import com.crm.model.vo.systemManager.CallManagerVO;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.systemManager.CallManagerDbService;
import com.crm.system.service.systemManager.CallManagerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;

/**
 * @Author renshaorong
 * @Date 2021/04/20 11:34 上午
 */
@Service
public class CallManagerServiceImpl implements CallManagerService {

    @Autowired
    private CallManagerDbService callManagerDbService;

    @Autowired
    private UserAccountDbService userAccountDbService;

    /**
     * 根据当前登陆用户获取用户权限下的呼叫信息
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @param callManagerQO
     * @return
     */
    @Override
    public DhPageInfo<CallManagerVO> getCallListsByUser(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, CallManagerQO callManagerQO) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());

        //增加删除状态查询条件(0:正常;1:已删除)
        callManagerQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("a.create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }

        if(!rs) {
            //普通管理员
            callManagerQO.setCompanyId(userAccount.getCompanyId());
        }
        List<CallManagerVO> callManagerList  = callManagerDbService.getAllCallLists(callManagerQO, order.toString());
        PageInfo<CallManagerVO> pageInfo = new PageInfo<CallManagerVO>(callManagerList);
        return new DhPageInfo<CallManagerVO>(pageInfo, callManagerList);
    }

    /**
     * 保存绑定信息
     * @param callManagerQO
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public boolean saveBindUser(CallManagerQO callManagerQO) {
        CallManager callManager = new CallManager();
        //set相关值，包括所有人ID及主键ID
        callManager.setCallId(callManagerQO.getCallId());
        callManager.setAccountId(callManagerQO.getAccountId());
        //验证该用户是否绑定了别的呼叫信息，如有，需解绑
        List<CallManager> callManagerList = callManagerDbService.getCallListByAccountId(callManagerQO.getAccountId());
        for(CallManager callManager1 : callManagerList){
            this.cleanUserAccountId(callManager1.getCallId());
        }

        //保存
        return callManagerDbService.updateByCallIdSelective(callManager);
    }

    /**
     * 解绑
     * @param callId
     * @return
     */
    @Override
    public boolean cleanUserAccountId(String callId) {
        CallManager callManager = callManagerDbService.selectByPrimaryKey(callId);
        callManager.setAccountId(null);
        return callManagerDbService.updateByCallId(callManager);
    }

    /**
     * 禁用
     * @param callId
     * @return
     */
    @Override
    public boolean disableByCallId(String callId) {
        CallManager callManager = callManagerDbService.selectByPrimaryKey(callId);
        callManager.setUseStatus((short) 1);
        //禁用要解绑
        callManager.setAccountId(null);
        return callManagerDbService.updateByCallId(callManager);
    }

    /**
     * 可用
     * @param callId
     * @return
     */
    @Override
    public boolean availableByCallId(String callId) {
        CallManager callManager = callManagerDbService.selectByPrimaryKey(callId);
        callManager.setUseStatus((short) 0);//可用0
        return callManagerDbService.updateByCallId(callManager);
    }

    /**
     * 获取呼叫信息（用于下拉框）
     * @param type
     * @return
     */
    @Override
    public List<CallManagerVO> getCallListsByUserList(Short type,String accountId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());

        CallManagerQO callManagerQO = new CallManagerQO();
        callManagerQO.setType(type);
        callManagerQO.setIsBlock((short) 1);//0不屏蔽/1屏蔽

        //增加删除状态查询条件(0:正常;1:已删除)
        callManagerQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        callManagerQO.setUseStatus((short) 0);

        StringBuilder order = new StringBuilder();
        order.append("a.create_tm ").append("asc");

        if(!rs) {
            //普通管理员
            callManagerQO.setCompanyId(userAccount.getCompanyId());
        }else{
            UserAccount checkUser = userAccountDbService.selectUserAccountByAccountId(accountId);
            callManagerQO.setCompanyId(checkUser.getCompanyId());
        }

        List<CallManagerVO> callManagerList  = callManagerDbService.getAllCallLists(callManagerQO, order.toString());
        return callManagerList;
    }

    /**
     * 账号管理页面绑定号码
     * @param callManagerQO
     * @return
     */
    @Override
    public boolean bindCallId(CallManagerQO callManagerQO) {
        if("random".equals(callManagerQO.getCallId())){//随机分配
            //获取该分类下可被绑定的信息列表
            List<CallManagerVO> callManagerVOS = this.getCallListsByUserList(callManagerQO.getType(),callManagerQO.getAccountId());
            //获取随机数位置的callId赋值给callManagerQO
            Random ra =new Random();
            callManagerQO.setCallId(callManagerVOS.get(ra.nextInt(callManagerVOS.size())).getCallId());
        }
        //绑定
        return this.saveBindUser(callManagerQO);
    }

    /**
     * 批量禁用
     * @param callIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public boolean batchDisable(List<String> callIds) {
        boolean b = true;
        for(String callId : callIds){
            b = b && this.disableByCallId(callId);
        }
        return b;
    }

    /**
     * 获取给定用户绑定的信息列表
     * @param accountId
     * @return
     */
    @Override
    public List<CallManager> getCallListByAccountId(String accountId) {
        return callManagerDbService.getCallListByAccountId(accountId);
    }

    /**
     * 拨打电话-线路切换获取随机号码
     * @Author pym
     * @Date  2021/5/26 8:38
     * @param type 号码类型 0、中继号 1、本地号 2、全国号
     * @return {@link {java.lang.String}}
     */
    @Override
    public String getRandomTelephoneNumber(String type) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String companyId = userAccount.getCompanyId();
        List<CallManager> callManagerList = null;
        String telephoneNumber = "";
        if ("2".equals(type)) {
            //全国线路
            callManagerList = callManagerDbService.getRandomTelephoneNumber(type, null);
        } else if ("1".equals(type)) {
            //本地线路
            callManagerList = callManagerDbService.getRandomTelephoneNumber(type, companyId);
        }
        if (callManagerList != null && callManagerList.size() >0) {
            Random ra =new Random();
            telephoneNumber = callManagerList.get(ra.nextInt(callManagerList.size())).getTelephoneNumber();
        }
        return telephoneNumber;
    }

}
